<template>
	<view class="invite_container">
		<navigator hover-class="none" url="/pages/common/pages/richtext?key=invitation_rules"
			class="pf t_8 r_0 zi_10 plr_8 lh_32 fc_fff fc tip" style="background-color: rgba(0,0,0,0.35);">
			邀请规则
		</navigator>
		<navigator hover-class="none" url="/pages/index/index" open-type="reLaunch"
			class="pf r_0 zi_10 plr_8 lh_32 fc_primary fc tip" style="background: rgba(254,90,28,0.25);top: 898rpx;">
			{{'<<回到首页'}}
		</navigator>
		<view class="img_list_wrap mt_52">
			<u-swiper :list="canvasList" previousMargin="76rpx" nextMargin="76rpx" imgMode="aspectFit" circular
				:autoplay="false" radius="16rpx" height="994rpx" @change="handleChangeImg"></u-swiper>
		</view>
		<view class="pf b_0 l_0 r_0 pbsafe_7 pt_7 plr_19 bc_fff fx fx_nw jcb">
			<button class="block_btn select_item fc_666 fx fx_col aic fx_1 fx_sh" @click="handleClick('circle')">
				<view class="fx aic jcc width_52 height_52 bc_fa mb_8 br_12">
					<image class="w100 h100" src="@/static/images/qrcode_ico_share_friends.png" mode=""></image>
				</view>
				<text class="mt_8">
					分享到朋友圈
				</text>
			</button>
			<button class="block_btn select_item fc_666 fx fx_col aic fx_1 fx_sh" open-type="share">
				<view class="fx aic jcc width_52 height_52 bc_fa mb_8 br_12">
					<image class="w100 h100" src="@/static/images/qrcode_ico_share_wechat.png" mode=""></image>
				</view>
				<text class="mt_8">
					分享给微信好友
				</text>
			</button>
			<button class="block_btn select_item fc_666 fx fx_col aic fx_1 fx_sh" @click="handleClick('download')">
				<view class="fx aic jcc width_52 height_52 bc_fa mb_8 br_12">
					<image class="w100 h100" src="@/static/images/qrcode_ico_share_qq.png" mode=""></image>
				</view>
				<text class="mt_8">
					保存图片
				</text>
			</button>
		</view>
		<canvas style="width: 572rpx;height:994rpx;" :canvas-id="'canvas-'+index" v-for="item,index in list"
			:key="index"></canvas>
		<view class="pf t_0 l_0 b_0 r_0" style="background: rgba(0,0,0,0.65);z-index: 1001" v-if="guideVisible"
			@click="guideVisible=false">
			<image class="width_120 height_120" style="padding-left:414rpx" src="@/static/images/share_line.png"
				mode="">
			</image>
			<view class="fb fz_16 fc_fff" style="padding-left:240rpx">
				<view>
					1、点击右上角“··· ”
				</view>
				<view class="mt_8 fx aic">
					<text>2、点击</text>
					<image class="width_44 height_44 plr_7" src="@/static/images/share_timeline.png"></image>
					<text>分享到朋友圈</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import shareMixin from '@/mixins/share.js'
	import canvasUtils from '@/utils/canvas'
	import api from '@/service/config/api.js'
	import base64src from '@/utils/base64src.js'
	import {
		mapState
	} from 'vuex'
	export default {
		mixins: [shareMixin],
		data() {
			return {
				list: [],
				canvasList: [],
				imgList: [],
				currentImg: 0,
				devicePixelRatio: 1,
				// userInfo: this.$storage.getItem('basicUnserInfo') || {},
				guideVisible: false,
				sharePath: '/pages/index/index',
				shareTitle: '您的好友分享了一个家装电商平台，快注册体验吧~',
				shareImageUrl: '',
				dataParams: {
					shareId: this.$store.state.userInfo.customerId
				}, // 二维码参数
			}
		},
		computed: {
			...mapState(['userInfo'])
		},
		onLoad() {
			uni.getSystemInfo({
				success: (res) => {
					this.devicePixelRatio = res.devicePixelRatio
					this.$nextTick(() => {
						this.getInviteList()
					})
				}
			})
		},
		methods: {
			getInviteList() {
				uni.showLoading({
					title: '海报生成中',
					mask: true
				});
				//TODO 测试
				// api.get(this.$store.state.appType==this.$base.ADMIN_TYPE?'/base/tInviteSet/item/list':'/base/tInviteSet/queryList', {}, {
				// 	noHideLoading: true
				// }).then(res1 => {
				// 	this.list = res1.data
				// 	if (res1.data && res1.data.length) {
				// 		this.imgList = res1.data.map(item => item.url)
				// 		this.shareImageUrl = this.imgList[0]
				// 	}
				// 	Promise.all([...this.list.map((item, index) => canvasUtils.InviteCanvas([item.url,
				// 			item.url
				// 		],
				// 		`canvas-${index}`,
				// 		this.userInfo.nickName, this.userInfo.customerId, this
				// 		.devicePixelRatio))]).then(res2 => {
				// 		uni.hideLoading();
				// 		this.canvasList = res2
				// 	}).catch(() => {
				// 		uni.hideLoading();
				// 	})
				// }).catch(() => {
				// 	uni.hideLoading();
				// })
				// return
				api.post('/user/api/auth/getWechatQrCode', {
					params: this.dataParams,
					page: 'pages/account/pages/login',
					width: 280
				}, {
					noHideLoading: true
				}).then(res => {
					if (res.data) {
						base64src(res.data).then(path => {
								api.get('/base/tInviteSet/item/list', {}, {
									noHideLoading: true
								}).then(res1 => {
									this.list = res1.data
									if (res1.data && res1.data.length) {
										this.imgList = res1.data.map(item => item.url)
										this.shareImageUrl = this.imgList[0]
										Promise.all([...this.imgList.map((item, index) => canvasUtils
											.InviteCanvas([item,
													path
												],
												`canvas-${index}`,
												this.userInfo.nickName || '', this.userInfo
												.customerId, this
												.devicePixelRatio))]).then(res2 => {
											uni.hideLoading();
											this.canvasList = res2
										}).catch(() => {
											uni.hideLoading();
											setTimeout(() => {
												this.$utils.showToast('图片生成失败')
											}, 1000)
										})
									}
								})
							})
							.catch(() => {
								uni.hideLoading();
								setTimeout(() => {
									this.$utils.showToast('图片生成失败')
								}, 1000)
							})
					}
				}).catch(() => {
					uni.hideLoading();
					setTimeout(() => {
						this.$utils.showToast('图片生成失败')
					}, 1000)
				})
			},
			handleChangeImg({
				current
			}) {
				this.currentImg = current
				this.shareImageUrl = this.imgList[current]
			},
			handleClick(type) {
				// api.post('/goods/api/product/addShareStatistics', {
				// 	...this.$store.state.userInfo.customerId ? {
				// 		customerId: this.$store.state.userInfo.customerId
				// 	} : {},
				// 	userType: this.userInfo.identityType || 1
				// }, {
				// 	noHideLoading: false,
				// 	noToast: false
				// })
				if (type == 'download') {
					if (!this.canvasList.length || !this.canvasList[this.currentImg]) {
						this.$utlis.showToast('图片保存失败')
						return
					}
					var that = this
					uni.getSetting({
						success(res) {
							if (res.authSetting['scope.writePhotosAlbum']) {
								// 已经获得授权，直接存储
								that.saveImg();
							} else if (res.authSetting['scope.writePhotosAlbum'] === undefined) {
								// 第一次运行，授权未定义，可以直接保存，系统会一次性询问用户权限
								that.saveImg();
							} else {
								// 用户拒绝授权后，打开设置页可以看到授权提示开关
								uni.openSetting({
									success(res) { // 用户授权
										if (res.authSetting['scope.writePhotosAlbum']) {
											that.saveImg();
										} else { // 用户拒绝授权
											that.setData({
												displayLoading: "none"
											})
											that.$utils.showToast('权限不足')
										}
									},
									fail(res) {
										that.setData({
											displayLoading: "none"
										})
										that.$utils.showToast('设置失败')
									}
								})
							}
						},
						fail(res) {
							console.log(res)
							that.setData({
								displayLoading: "none"
							})
							that.$utils.showToast('设置失败')
						}
					})
					return
				}
				if (type == 'circle') {
					this.guideVisible = true
					return
				}
			},
			saveImg() {
				uni.saveImageToPhotosAlbum({
					filePath: this.canvasList[this.currentImg],
					success: function(data) {
						uni.hideLoading();
						uni.showToast({
							title: '已保存至相册！',
							icon: 'success',
							duration: 2000
						})
					},
				})
			}
		}
	}
</script>

<style lang="scss">
	.u-swiper__wrapper__item__wrapper__image {
		width: 572rpx !important;
		height: 994rpx !important;
	}
</style>

<style lang="scss" scoped>
	.invite_container {
		.tip {
			border-radius: 40rpx 0px 0px 40rpx;
		}

		canvas {
			position: fixed;
			z-index: -5;
			left: -100vw;
			opacity: 0;
		}
	}
</style>